package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import com.changgou.oauth.util.GitHubConstant;
import com.changgou.oauth.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    private AuthService authService;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @PostMapping("/login")
    public Result<AuthToken> login(String username, String password, HttpServletResponse response){
        if (username==null&&username.length()==0)throw new RuntimeException("用户名不存在");
        if (password==null&&password.length()==0)throw new RuntimeException("密码为空");
        AuthToken authToken = authService.applyToken(username, password,false);
        //将jit存储到客户端cookie
        saveJIt2Cookie(authToken.getJti(),response);
        return new Result(true, StatusCode.OK,"登录成功");

    }

    private void saveJIt2Cookie(String jti,HttpServletResponse response) {
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }

}
